package br.com.jk.valealim.cartaotipo;

import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.JOptionPane;
import br.com.jk.util.Util;
import br.com.jk.util.Util.SomenteNumeros;
import br.com.jk.util.UtilException;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import net.sf.jasperreports.engine.JRException;

/**
 *
 * @author Camilo
 */
public class CartaoTipoJDialog extends javax.swing.JDialog {

  private static CartaoTipoJDialog cartaoTipoJDialog;
  // Model da tabela
  CartaoTipoTableModel cartaoTM = new CartaoTipoTableModel();
  List<CartaoTipo> lstCartao;
  private Boolean modoConsulta = false;
  private Boolean modoConsultaExt = false;
  public JTextField jtfIdPesquisa;
  public JTextField jtfNomePesquisa;
  private int colunaSel;
  private SomenteNumeros docTelefone = new Util().new SomenteNumeros();
  private SomenteNumeros docCod = new Util().new SomenteNumeros();
  private SomenteNumeros docEstab = new Util().new SomenteNumeros();
  private SomenteNumeros docPrazo = new Util().new SomenteNumeros();

  /**
   * Creates new form CartaoTipoJDialog
   */
  private CartaoTipoJDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    setLocationRelativeTo(null);
    jlFiltro.setVisible(false);
    listar();
  }

  public static CartaoTipoJDialog getInstance(java.awt.Frame parent, boolean modal) {
    if (cartaoTipoJDialog == null) {
      cartaoTipoJDialog = new CartaoTipoJDialog(parent, modal);
    }
    return cartaoTipoJDialog;
  }

  private CartaoTipoJDialog(java.awt.Frame parent, boolean modal, JTextField id, JTextField name) {
    super(parent, modal);
    this.jtfIdPesquisa = id;
    this.jtfNomePesquisa = name;
    this.modoConsultaExt = true;
    initComponents();
    jlFiltro.setVisible(false);
    setLocationRelativeTo(null);
    listar();
  }
  
  public static CartaoTipoJDialog getInstance(java.awt.Frame parent, boolean modal, JTextField id, JTextField name) {
    if (cartaoTipoJDialog == null) {
      cartaoTipoJDialog = new CartaoTipoJDialog(parent, modal, id, name);
    }
    return cartaoTipoJDialog;
  }

  /**
   * This method is called from within the constructor to initialize the form. WARNING: Do
   * NOT modify this code. The content of this method is always regenerated by the Form
   * Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    JtbMaster = new javax.swing.JToolBar();
    JbNovo = new javax.swing.JButton();
    JbSalvar = new javax.swing.JButton();
    JbEditar = new javax.swing.JButton();
    JbCancelar = new javax.swing.JButton();
    JbExcluir = new javax.swing.JButton();
    jSeparator2 = new javax.swing.JToolBar.Separator();
    JbPesquisar = new javax.swing.JButton();
    JbRelatorio = new javax.swing.JButton();
    jSeparator1 = new javax.swing.JToolBar.Separator();
    JbRefresh = new javax.swing.JButton();
    jlFiltro = new javax.swing.JLabel();
    jpDados = new javax.swing.JPanel();
    jLabel2 = new javax.swing.JLabel();
    jtfId = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();
    jtfCod = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jtfNome = new javax.swing.JTextField();
    jLabel4 = new javax.swing.JLabel();
    jtfTaxa = new javax.swing.JTextField();
    jtfTelefone = new javax.swing.JTextField();
    jLabel12 = new javax.swing.JLabel();
    jtfEstab = new javax.swing.JTextField();
    jLabel5 = new javax.swing.JLabel();
    jtfPrazo = new javax.swing.JTextField();
    jLabel6 = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jtCartaoTipo = new javax.swing.JTable();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Cadastro de Bandeiras de Cartões");
    setResizable(false);
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosed(java.awt.event.WindowEvent evt) {
        formWindowClosed(evt);
      }
    });

    JtbMaster.setRollover(true);

    JbNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-new.png"))); // NOI18N
    JbNovo.setToolTipText("Novo Registro");
    JbNovo.setFocusable(false);
    JbNovo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbNovo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbNovo.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbNovoActionPerformed(evt);
      }
    });
    JtbMaster.add(JbNovo);

    JbSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-save-hd.png"))); // NOI18N
    JbSalvar.setToolTipText("Salvar Registro");
    JbSalvar.setEnabled(false);
    JbSalvar.setFocusable(false);
    JbSalvar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbSalvar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbSalvar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbSalvarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbSalvar);

    JbEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-edit.png"))); // NOI18N
    JbEditar.setToolTipText("Alterar registro");
    JbEditar.setEnabled(false);
    JbEditar.setFocusable(false);
    JbEditar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbEditar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbEditar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbEditarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbEditar);

    JbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/dialog-cancel.png"))); // NOI18N
    JbCancelar.setToolTipText("Cancelar o procedimento");
    JbCancelar.setEnabled(false);
    JbCancelar.setFocusable(false);
    JbCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbCancelar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbCancelarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbCancelar);

    JbExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/archive-remove.png"))); // NOI18N
    JbExcluir.setToolTipText("Excluir o registro");
    JbExcluir.setEnabled(false);
    JbExcluir.setFocusable(false);
    JbExcluir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbExcluir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbExcluir.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbExcluirActionPerformed(evt);
      }
    });
    JtbMaster.add(JbExcluir);
    JtbMaster.add(jSeparator2);

    JbPesquisar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/edit-find.png"))); // NOI18N
    JbPesquisar.setToolTipText("PESQUISA. (Space)");
    JbPesquisar.setEnabled(false);
    JbPesquisar.setFocusable(false);
    JbPesquisar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbPesquisar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbPesquisar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbPesquisarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbPesquisar);

    JbRelatorio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/report.png"))); // NOI18N
    JbRelatorio.setToolTipText("Relatórios");
    JbRelatorio.setEnabled(false);
    JbRelatorio.setFocusable(false);
    JbRelatorio.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRelatorio.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRelatorio.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRelatorioActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRelatorio);
    JtbMaster.add(jSeparator1);

    JbRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/view-refresh.png"))); // NOI18N
    JbRefresh.setToolTipText("Atualizar registros da lista");
    JbRefresh.setFocusable(false);
    JbRefresh.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRefresh.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRefresh.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRefreshActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRefresh);

    jlFiltro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/task-attempt.png"))); // NOI18N
    jlFiltro.setToolTipText("FILTRO ATIVO. Clique no botão Atualizar para restaurar");
    JtbMaster.add(jlFiltro);

    jpDados.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Dados"));

    jLabel2.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel2.setText("Id");

    jtfId.setEditable(false);
    jtfId.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfId.setEnabled(false);

    jLabel1.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel1.setText("Cod");

    jtfCod.setDocument(docCod);
    jtfCod.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfCod.setEnabled(false);
    jtfCod.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfCodKeyPressed(evt);
      }
    });

    jLabel3.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel3.setText("Nome");

    jtfNome.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfNome.setEnabled(false);
    jtfNome.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusLost(java.awt.event.FocusEvent evt) {
        jtfNomeFocusLost(evt);
      }
    });
    jtfNome.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfNomeKeyPressed(evt);
      }
      public void keyReleased(java.awt.event.KeyEvent evt) {
        jtfNomeKeyReleased(evt);
      }
    });

    jLabel4.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel4.setText("Taxa %");

    jtfTaxa.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfTaxa.setEnabled(false);
    jtfTaxa.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusLost(java.awt.event.FocusEvent evt) {
        jtfTaxaFocusLost(evt);
      }
    });
    jtfTaxa.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfTaxaKeyPressed(evt);
      }
    });

    jtfTelefone.setDocument(docTelefone);
    jtfTelefone.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfTelefone.setEnabled(false);
    jtfTelefone.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        jtfTelefoneFocusGained(evt);
      }
      public void focusLost(java.awt.event.FocusEvent evt) {
        jtfTelefoneFocusLost(evt);
      }
    });
    jtfTelefone.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfTelefoneKeyPressed(evt);
      }
    });

    jLabel12.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel12.setText("Estab");

    jtfEstab.setDocument(docEstab);
    jtfEstab.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfEstab.setEnabled(false);
    jtfEstab.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfEstabKeyPressed(evt);
      }
    });

    jLabel5.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel5.setText("Telefone");

    jtfPrazo.setDocument(docPrazo);
    jtfPrazo.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfPrazo.setEnabled(false);
    jtfPrazo.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfPrazoKeyPressed(evt);
      }
    });

    jLabel6.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel6.setText("Prazo");

    javax.swing.GroupLayout jpDadosLayout = new javax.swing.GroupLayout(jpDados);
    jpDados.setLayout(jpDadosLayout);
    jpDadosLayout.setHorizontalGroup(
      jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jpDadosLayout.createSequentialGroup()
        .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addGroup(jpDadosLayout.createSequentialGroup()
            .addComponent(jtfEstab, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jtfTaxa))
          .addGroup(jpDadosLayout.createSequentialGroup()
            .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jtfId, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(jLabel2))
            .addGap(6, 6, 6)
            .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jtfCod, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(jLabel1))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel5)
              .addComponent(jtfTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)))
          .addGroup(jpDadosLayout.createSequentialGroup()
            .addComponent(jLabel12)
            .addGap(124, 124, 124)
            .addComponent(jLabel4)))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jLabel6)
          .addComponent(jtfPrazo, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jtfNome, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jLabel3))
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    jpDadosLayout.setVerticalGroup(
      jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jpDadosLayout.createSequentialGroup()
        .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel2)
          .addComponent(jLabel1)
          .addComponent(jLabel3)
          .addComponent(jLabel5))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jtfId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jtfCod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jtfNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jtfTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel4)
          .addComponent(jLabel12)
          .addComponent(jLabel6))
        .addGap(1, 1, 1)
        .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jtfTaxa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jtfEstab, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jtfPrazo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addContainerGap(19, Short.MAX_VALUE))
    );

    jtCartaoTipo.setModel(cartaoTM);
    jtCartaoTipo.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtCartaoTipo.getSelectedRow();
        selecionado();
      }
    });

    jtCartaoTipo.getColumnModel().getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtCartaoTipo.getSelectedColumn();
        selecionado();
      }
    });
    jtCartaoTipo.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        jtCartaoTipoMouseClicked(evt);
      }
    });
    jtCartaoTipo.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtCartaoTipoKeyPressed(evt);
      }
    });
    jScrollPane1.setViewportView(jtCartaoTipo);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(JtbMaster, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addGroup(layout.createSequentialGroup()
        .addGap(4, 4, 4)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addComponent(jScrollPane1)
          .addComponent(jpDados, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(JtbMaster, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(jpDados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addContainerGap())
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void JbNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbNovoActionPerformed
    novo();
  }//GEN-LAST:event_JbNovoActionPerformed

  private void JbSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbSalvarActionPerformed
    salvar();
  }//GEN-LAST:event_JbSalvarActionPerformed

  private void JbEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbEditarActionPerformed
    editar();
  }//GEN-LAST:event_JbEditarActionPerformed

  private void JbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbCancelarActionPerformed
    cancelar();
  }//GEN-LAST:event_JbCancelarActionPerformed

  private void JbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbExcluirActionPerformed
    excluir();
  }//GEN-LAST:event_JbExcluirActionPerformed

  private void JbPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbPesquisarActionPerformed
    pesquisar();
  }//GEN-LAST:event_JbPesquisarActionPerformed

  private void JbRelatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRelatorioActionPerformed
    try {
      ThreadReport thReport = new ThreadReport();
      thReport.start();
    } catch (Exception e) {
      Util.msgErro(e, "Erro ao gerar o relatório");
    }
  }//GEN-LAST:event_JbRelatorioActionPerformed

  private void JbRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRefreshActionPerformed
    listar();
    jlFiltro.setVisible(false);
    JbPesquisar.setEnabled(false);
  }//GEN-LAST:event_JbRefreshActionPerformed

  private void jtfCodKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfCodKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfTelefone.requestFocus();
    }
  }//GEN-LAST:event_jtfCodKeyPressed

  private void jtfNomeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfNomeKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfEstab.requestFocus();
    }
  }//GEN-LAST:event_jtfNomeKeyPressed

  private void jtfTaxaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfTaxaKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfPrazo.requestFocus();
    }
  }//GEN-LAST:event_jtfTaxaKeyPressed

  private void jtfTelefoneKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfTelefoneKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfNome.requestFocus();
    }
  }//GEN-LAST:event_jtfTelefoneKeyPressed

  private void jtfEstabKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfEstabKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfTaxa.requestFocus();
    }
  }//GEN-LAST:event_jtfEstabKeyPressed

  private void jtCartaoTipoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtCartaoTipoMouseClicked
    if (cartaoTM.getRowCount() > 0 && (jtfId.getText() != null && jtfNome != null)) {
      habilitaJb(true, false, true, false, true);
      habilitaJtf(false);
      jtfId.setEditable(false);
      limpar();
      modoConsulta = false;
      selecionado();
    }
  }//GEN-LAST:event_jtCartaoTipoMouseClicked

  private void jtfPrazoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfPrazoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      this.salvar();
    }
  }//GEN-LAST:event_jtfPrazoKeyPressed

  private void jtCartaoTipoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtCartaoTipoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (modoConsultaExt) {
        this.selecionarRegistro();
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_SPACE) {
      if (modoConsulta) {
        this.pesquisar();
      }
    }
  }//GEN-LAST:event_jtCartaoTipoKeyPressed

  private void jtfTaxaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfTaxaFocusLost
    jtfTaxa.setText(jtfTaxa.getText().replaceAll(",", "."));
  }//GEN-LAST:event_jtfTaxaFocusLost

  private void jtfNomeFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfNomeFocusLost
  }//GEN-LAST:event_jtfNomeFocusLost

  private void jtfNomeKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfNomeKeyReleased
    Util.setFirstLetterUpperCase(jtfNome, jtfNome.getSelectionStart());
  }//GEN-LAST:event_jtfNomeKeyReleased

  private void jtfTelefoneFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfTelefoneFocusLost
    try {
      jtfTelefone.setText(Util.formatTelefone(jtfTelefone.getText()));
    } catch (UtilException e) {
      jtfTelefone.requestFocus();
      Util.msgAdv(e, "");
    }
  }//GEN-LAST:event_jtfTelefoneFocusLost

  private void jtfTelefoneFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfTelefoneFocusGained
    jtfTelefone.setText(jtfTelefone.getText().replaceAll("[() -]+", ""));
  }//GEN-LAST:event_jtfTelefoneFocusGained

  private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    cartaoTipoJDialog = null;
  }//GEN-LAST:event_formWindowClosed

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(CartaoTipoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(CartaoTipoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(CartaoTipoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(CartaoTipoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        CartaoTipoJDialog dialog = new CartaoTipoJDialog(new javax.swing.JFrame(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
          @Override
          public void windowClosing(java.awt.event.WindowEvent e) {
            System.exit(0);
          }
        });
        dialog.setVisible(true);
      }
    });
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton JbCancelar;
  private javax.swing.JButton JbEditar;
  private javax.swing.JButton JbExcluir;
  private javax.swing.JButton JbNovo;
  private javax.swing.JButton JbPesquisar;
  private javax.swing.JButton JbRefresh;
  private javax.swing.JButton JbRelatorio;
  private javax.swing.JButton JbSalvar;
  private javax.swing.JToolBar JtbMaster;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel12;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JLabel jLabel5;
  private javax.swing.JLabel jLabel6;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JToolBar.Separator jSeparator1;
  private javax.swing.JToolBar.Separator jSeparator2;
  private javax.swing.JLabel jlFiltro;
  private javax.swing.JPanel jpDados;
  private javax.swing.JTable jtCartaoTipo;
  private javax.swing.JTextField jtfCod;
  private javax.swing.JTextField jtfEstab;
  private javax.swing.JTextField jtfId;
  private javax.swing.JTextField jtfNome;
  private javax.swing.JTextField jtfPrazo;
  private javax.swing.JTextField jtfTaxa;
  private javax.swing.JTextField jtfTelefone;
  // End of variables declaration//GEN-END:variables

  private void setJtCartaoTipoTM(List<CartaoTipo> ct) {
    while (cartaoTM.getRowCount() > 0) {
      cartaoTM.remove(0);
    }
    if (!ct.isEmpty()) {
      cartaoTM.adicionaLista(ct);
    }
  }

  private void setJtCartaoTipoTM(CartaoTipo ct) {
    while (cartaoTM.getRowCount() > 0) {
      cartaoTM.remove(0);
    }
    if (ct != null) {
      cartaoTM.adiciona(ct);
    }
  }

  private void novo() {
    limpar();
    habilitaJb(false, true, false, true, false);
    habilitaJtf(true);
    jtfCod.requestFocus();
  }

  private void salvar() {
    try {
      CartaoTipo cartao = criaObjetos();
      CartaoTipoRn ctRn = new CartaoTipoRn();

      //faz a conexão com o bd e salva os registros
      ctRn.salvar(cartao);

      listar();
      habilitaJb(true, false, false, false, false);
      habilitaJtf(false);
      limpar();
    } catch (Exception e) {
      Util.msgErro(e, "Ocorreu erro ao tentar gravar no banco de dados");
    }
  }

  private void listar() {
    CartaoTipoRn matrizRn = new CartaoTipoRn();
    setJtCartaoTipoTM(lstCartao = matrizRn.listar());
  }

  private void limpar() {
    jtfEstab.setText(null);
    jtfTaxa.setText(null);
    jtfId.setText(null);
    jtfTelefone.setText(null);
    jtfCod.setText(null);
    jtfNome.setText(null);
    jtfPrazo.setText(null);
  }

  /**
   * Determina quais os botões da barra de ferramentas ficará ativo
   *
   * @param novo
   * @param salvar
   * @param editar
   * @param cancelar
   * @param excluir
   */
  private void habilitaJb(Boolean novo, Boolean salvar, Boolean editar, Boolean cancelar,
          Boolean excluir) {
    JbNovo.setEnabled(novo);
    JbSalvar.setEnabled(salvar);
    JbEditar.setEnabled(editar);
    JbCancelar.setEnabled(cancelar);
    JbExcluir.setEnabled(excluir);
  }

  /**
   * Define se os JTextFields serão liberados para edição do usuário
   *
   * @param tf <b>True</b> - Habilitar; <b>False</b> - Desabilitar;
   */
  private void habilitaJtf(Boolean tf) {
    jtfEstab.setEnabled(tf);
    jtfTaxa.setEnabled(tf);
    jtfTelefone.setEnabled(tf);
    jtfCod.setEnabled(tf);
    jtfNome.setEnabled(tf);
    jtfPrazo.setEnabled(tf);
  }

  private void selecionado() {
    int linhaSel = jtCartaoTipo.getSelectedRow();
//    verifica se realmente há uma linha selecionada
    if (linhaSel >= 0) {
      int columSel = jtCartaoTipo.getSelectedColumn();
      boolean pesq = setEnabledPesquisa(columSel);

      jtfId.setText(this.cartaoTM.getValueAt(linhaSel, 0).toString());
      jtfCod.setText(this.cartaoTM.getValueAt(linhaSel, 1).toString());
      jtfNome.setText(this.cartaoTM.getValueAt(linhaSel, 2).toString());
      jtfTaxa.setText(this.cartaoTM.getValueAt(linhaSel, 5).toString());
      jtfTelefone.setText(this.cartaoTM.getValueAt(linhaSel, 3).toString());
      jtfEstab.setText(this.cartaoTM.getValueAt(linhaSel, 4).toString());
      jtfPrazo.setText(this.cartaoTM.getValueAt(linhaSel, 6).toString());

      modoConsulta = pesq;
      JbPesquisar.setEnabled(pesq);
    }
  }

  private void editar() {
    habilitaJb(false, true, false, true, false);
    habilitaJtf(true);
    jtfCod.requestFocus();
  }

  private void excluir() {
//    Define os objetos
    CartaoTipoRn ctRn = new CartaoTipoRn();
    CartaoTipo ct = criaObjetos();
//    Executa o procedimento no BD
    ctRn.excluir(ct);

    listar();
    limpar();
  }

  /**
   * Cria instâncias dos objetos para serem enviados para o BD
   *
   * @return
   */
  private CartaoTipo criaObjetos() {
    CartaoTipo c = new CartaoTipo();

    //preenche o objeto com os dados dos jtextfield
    if (!jtfId.getText().isEmpty()) {
      c.setId(Integer.parseInt(jtfId.getText()));
    }
    c.setCod(jtfCod.getText());
    c.setNome(jtfNome.getText());
    c.setTelefone(jtfTelefone.getText());
    c.setEstabelecimento(Integer.parseInt(jtfEstab.getText()));
    c.setTaxa(Double.parseDouble(jtfTaxa.getText()));
    c.setPrazo(Integer.parseInt(jtfPrazo.getText()));

    return c;
  }

  private void cancelar() {
    limpar();
    habilitaJb(true, false, false, false, false);
    habilitaJtf(false);
    if (modoConsulta) {
      modoConsulta = false;
    } else {
      listar();
    }
  }

  private void report() throws JRException, Exception {
    CartaoTipoReport mReport = new CartaoTipoReport();
    mReport.geraRelatorio1();
  }

  private void pesquisar() {
    if (modoConsulta) {
      String criterio = JOptionPane.showInputDialog(null, "Digite o critério da pesquisa:",
              "Pesquisa", JOptionPane.INFORMATION_MESSAGE);
      if (criterio == null || criterio.isEmpty()) {
        JbPesquisar.setEnabled(false);
      } else {
        limpar();

        CartaoTipoRn ctrn = new CartaoTipoRn();
//        Verifica qual é o tipo de campo e executa a consulta específica

        switch (colunaSel) {
          case CartaoTipoTableModel.COLUMN_COD_ID:
            setJtCartaoTipoTM(ctrn.carregar(Integer.parseInt(criterio)));
            break;
          case CartaoTipoTableModel.COLUMN_COD_COD:
            setJtCartaoTipoTM(ctrn.pesquisaPadrao(CartaoTipoDaoHibernate.PROPERTY_COD, criterio));
            break;
          case CartaoTipoTableModel.COLUMN_COD_NOME:
            setJtCartaoTipoTM(ctrn.pesquisaPadrao(CartaoTipoDaoHibernate.PROPERTY_NOME, criterio));
            break;
          case CartaoTipoTableModel.COLUMN_COD_PRAZO:
            int i = Integer.parseInt(criterio);
            setJtCartaoTipoTM(ctrn.pesquisaPadrao(CartaoTipoDaoHibernate.PROPERTY_PRAZO, i));
            break;
          default:
            throw new AssertionError();
        }
        jlFiltro.setVisible(true);
      }
    }
  }

  private void getLarguraJtBanco() {
    int grade;
    int column = cartaoTM.getColumnCount();
    //JtBanco.getColumnModel().getSelectedColumnCount();
    for (int i = 0; i < column; i++) {
      grade = this.jtCartaoTipo.getColumnModel().getColumn(i).getPreferredWidth();
      System.out.println(grade);
    }
  }

  class ThreadReport extends Thread {

    @Override
    public void run() {
      try {
        report();
      } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage());
      }
    }
  }

  public void selecionarRegistro() {
    int linhaSel = jtCartaoTipo.getSelectedRow();
    jtfIdPesquisa.setText(this.cartaoTM.getValueAt(linhaSel, 0).toString());
    jtfNomePesquisa.setText(this.cartaoTM.getValueAt(linhaSel, 2).toString());
    this.modoConsultaExt = false;
    this.dispose();
  }

  /**
   * Habilita a pesquisa somente para os campos configurados nesse método
   *
   * @param coluna Índice da coluna da qual se deseja efetuar a pesquisa
   * @return Se o campo estiver habilitado permite a pesquisa. O default é: false;
   */
  public boolean setEnabledPesquisa(int coluna) {
    colunaSel = coluna;
    switch (coluna) {
      case CartaoTipoTableModel.COLUMN_COD_ID:
        return true;
      case CartaoTipoTableModel.COLUMN_COD_COD:
        return true;
      case CartaoTipoTableModel.COLUMN_COD_NOME:
        return true;
      case CartaoTipoTableModel.COLUMN_COD_PRAZO:
        return true;
      default:
        return false;
    }
  }
}
